/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-11 17:52:20
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-03-12 13:03:03
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Alert,
  AutoComplete,
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  List,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Tag,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import moment from 'moment';
import SimpleTable from 'components/SimpleTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './enterprise.less';

const FormItem = Form.Item;

const { Option } = Select;

const { RangePicker } = DatePicker;

const CreateU = Form.create()(prop => {
  const { dispatch, form, record } = prop;
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  const uploadProps = {
    name: 'file',
    action: 'https://service-api.lisonhealth.com/upload',
    showUploadList: false,
    headers: {
      Authorization: localStorage.getItem('authorization-token'),
    },
    listType: 'picture-card',
    onChange: info => {
      if (info.file.status === 'done') {
        const { success } = info.file.response;
        if (success) {
          message.success(`导入成功.`);
          const {
            file: {
              response: { data },
            },
          } = info;

          dispatch({
            type: 'serviceList/editImg',
            payload: { key: record.key, attachmentUrl: data },
          });

          //
          // this.setState({
          //   attachmentUrl: data,
          // });
        } else {
          message.success(`导入失败.`);
        }
      } else if (info.file.status === 'error') {
        message.error(`上传文件失败.`);
      }
    },
  };
  const uploadButton = (
    <div>
      <Icon style={{ width: '20px', height: '20px' }} type={'plus'} />
    </div>
  );

  return (
    <Upload {...uploadProps}>
      {record.attachmentUrl ? (
        <img src={record.attachmentUrl} alt="file" style={{ width: '20px', height: '20px' }} />
      ) : (
        uploadButton
      )}
    </Upload>
  );
});

@connect(
  ({
    companyStorePage,
    dict,
    contractList,
    enterpriseList,
    employeeList,
    extraItemList,
    institutionList,
    serviceList,
    loading,
  }) => ({
    companyStorePage,
    enterpriseList,
    dict,
    contractList,
    employeeList,
    extraItemList,
    institutionList,
    serviceList,
    loading: loading.models.companyStorePage,
  })
)
@Form.create()
export default class TableList extends PureComponent {
  state = {
    dataSource: [], // 企业名称 数据源
    result: [], // 企业名称 自动匹配结果
    companyId: '', // 企业id
    contractId: '', // 合同id
    contarctValue: '',
    type: 'add',
    imageUrl: '',
    stateLoading: '',
    attachmentUrl: '',
  };

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;

    let companyId = '';
    let id = '';

    // 查询员工详情
    if (query) {
      ({ companyId, id } = query);
      dispatch({
        type: 'serviceList/serviceDetail',
        payload: {
          id,
        },
      });

      dispatch({
        type: 'contractList/getList',
        payload: { companyId },
      });

      this.setState({
        type: 'edit',
      });
    }

    // 查询公司
    dispatch({
      type: 'companyStorePage/companyList',
      payload: {
        name: '',
      },
      callback: res => {
        const newList = res.data.map(v => {
          return <Option value={v.id}>{v.name}</Option>;
        });
        this.setState({
          dataSource: newList,
          result: newList,
        });
      },
    });

    // 清除
    dispatch({
      type: 'serviceList/clearServiceList',
    });
  }

  onSelect = v => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'contractList/getList',
      payload: { companyId: v },
    });

    this.setState(
      {
        companyId: v,
        contarctValue: '',
      },
      () => {
        dispatch({
          type: 'enterpriseList/positionList',
          payload: {
            companyId: v,
          },
        });
      }
    );

    form.setFieldsValue({ companyId: v });
  };

  onChangeH = (v, t) => {
    if (!t) {
      return;
    }
    const {
      props: { children },
    } = t;
    this.setState({
      contractId: v,
      contarctValue: children,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'serviceList/addServiceDetailList',
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      serviceList: { addServiceDetailList },
      location: { query },
    } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        ...fieldsValue,
        serviceDetailList: [...addServiceDetailList],
      };
      params.id = query ? query.id : '';

      dispatch({
        type:
          (query ? query.type : '') === 'edit'
            ? 'serviceList/serviceEdit'
            : 'serviceList/serviceAdd',
        payload: params,
        callback: res => {
          if (res.success) {
            if (res.success) {
              let secondsToGo = 3;
              const modal = Modal.success({
                title: (query ? query.type : '') === 'edit' ? '修改成功' : '新增成功',
                content: `将在${secondsToGo}秒后返回套餐服务列表页面`,
                okText: '知道了',
              });
              const timer = setInterval(() => {
                secondsToGo -= 1;
                modal.update({
                  content: `将在${secondsToGo}秒后返返回套餐服务列表页面`,
                });
              }, 1000);
              setTimeout(() => {
                clearInterval(timer);
                modal.destroy();
                dispatch(routerRedux.push('/Enterprise/service-list'));
              }, secondsToGo * 1000);
            } else {
              message.info(res.errorDesc);
            }
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  handleDelete = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'serviceList/deleteServiceList',
      payload: record,
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/Enterprise/service-list'));
  };

  handleInputChange = (e, r, n) => {
    let value = '';
    if (typeof e === 'string') {
      value = e;
    } else {
      value = e.target.value;
    }
    const { dispatch } = this.props;

    const newobj = { ...r };
    newobj[n] = value;
    dispatch({
      type: 'serviceList/editServiceList',
      payload: newobj,
    });
  };

  renderOptionsH = () => {
    const {
      contractList: { list },
    } = this.props;
    const options = list.map(v => <Option value={v.id}>{v.title}</Option>);
    return options;
  };

  render() {
    const {
      loading,
      form,
      extraItemList: { extraItemList, addExtraItemList },
      serviceList: { detailData, addServiceDetailList },
      dict: { dictList },
      institutionList: { dictInstitutionList },
    } = this.props;

    const { result, contarctValue, imageUrl, stateLoading, type } = this.state;
    const { getFieldDecorator } = form;

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        render: (v, r) => (
          <Input
            style={{ width: '80%' }}
            defaultValue={v}
            onChange={e => this.handleInputChange(e, r, 'name')}
          />
        ),
      },

      {
        title: '描述',
        dataIndex: 'description',
        render: (v, r) => (
          <Input
            style={{ width: '80%' }}
            defaultValue={v}
            onChange={e => this.handleInputChange(e, r, 'description')}
          />
        ),
      },
      {
        title: '详情',
        dataIndex: 'attachmentUrl',
        render: (v, r) => {
          return <CreateU record={r} {...this.props} />;
        },
      },
      {
        title: '操作',
        render: (val, record) => (
          <div>
            <a onClick={() => this.handleDelete(record)}>删除</a>
          </div>
        ),
      },
    ];
    const detailInfo = type == 'add' ? {} : detailData;

    return (
      <PageHeaderLayout>
        <Card
          bordered={false}
          style={{ paddingBottom: '20px' }}
          loading={loading}
          className={styles.serviceDetail}
        >
          <Alert message="套餐信息" type="info" />
          <Form layout="inline">
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="企业名称&#12288;">
                  {getFieldDecorator('companyId', {
                    initialValue: detailInfo?.companyId,
                    rules: [{ required: true, message: '请输入企业名称' }],
                  })(
                    <Select
                      showSearch
                      placeholder="输入企业名称查询"
                      style={{ width: 150 }}
                      optionFilterProp="children"
                      onChange={this.onSelect}
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {result}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={12} sm={24}>
                <FormItem label="合同名称">
                  {getFieldDecorator('contractId', {
                    initialValue: detailInfo?.contractId,
                    rules: [{ required: true, message: '请选择合同名称' }],
                  })(
                    <Select
                      placeholder="请选择"
                      style={{ width: 150 }}
                      onChange={this.onChangeH}
                      autoClearSearchValue
                      allowClear
                      value={contarctValue}
                    >
                      {this.renderOptionsH()}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col md={12} sm={24}>
                <FormItem label="服务名称">
                  {getFieldDecorator('name', {
                    initialValue: detailInfo?.name,
                    rules: [{ required: true, message: '请输入服务名称' }],
                  })(<Input />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={12} sm={24}>
                <FormItem label="服务描述">
                  {getFieldDecorator('description', {
                    initialValue: detailInfo?.description,
                    rules: [{ required: true, message: '请输入服务描述' }],
                  })(<Input par />)}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col md={6} sm={24}>
                <FormItem label="服务可选设置">
                  {getFieldDecorator('serviceChooseType', {
                    initialValue: detailInfo?.serviceChooseType,
                    rules: [{ required: true, message: '请选择服务可选设置' }],
                  })(
                    <Select placeholder="请选择" style={{ width: 88 }}>
                      <Option key={1}>{'<='}</Option>
                      <Option key={2}> {'='} </Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={6} sm={24}>
                <FormItem label="数量">
                  {getFieldDecorator('serviceChooseNum', {
                    initialValue: detailInfo?.serviceChooseNum,
                    rules: [{ required: true, message: '请输入数量' }],
                  })(<InputNumber />)}
                </FormItem>
              </Col>
            </Row>
          </Form>

          <Alert message="套餐服务明细" type="info" />
          <div style={{ margin: '10px 0' }}>
            <Button type="primary" icon="plus" onClick={this.handleAdd}>
              新增
            </Button>
          </div>

          <SimpleTable
            selectedRows={false}
            onSelectRow={false}
            loading={loading}
            data={{ list: addServiceDetailList }}
            columns={columns}
            onChange=""
            rowKey="key"
          />
        </Card>
        <div style={{ textAlign: 'center' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.handleSubmit}>
            提交
          </Button>
          <Button type="" onClick={this.handleCancel}>
            返回
          </Button>
        </div>
      </PageHeaderLayout>
    );
  }
}
